package com.android.lovely.aav

import com.airbnb.lottie.LottieAnimationView
import com.android.lovely.aav.discount.DiscountEventDispatcher
import com.android.lovely.aav.discount.DiscountInfoManager
import com.android.lovely.aav.discount.FileDownloader
import com.android.lovely.aav.discount.LottieFileLoader
import com.android.lovely.api.service.userService
import com.android.lovely.data.PayDetail
import com.android.lovely.data.SubPreferential
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.user.UserManager
import com.kotlin.extensions.appContext
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import java.io.File

/**
 * 充值活动管理类
 */
object PreferentialManager {
    private val discountInfoManager = DiscountInfoManager(userService, UserManager)
    private val fileDownloader = FileDownloader(appContext)
    private val lottieFileLoader = LottieFileLoader()
    private val eventDispatcher = DiscountEventDispatcher()

    var isSecondLevelPageShown = false

    private var isLoadingIcon = false

    private var isLoadingImage = false

    val eventFlow get() = eventDispatcher.discountFlow

    val isEnable: Boolean
        get() {
            val activity = discountInfoManager.discountInfo
            return activity?.actList?.firstOrNull()?.productList?.firstOrNull()?.appleId.isNullOrEmpty()
                .not() && iconFile != null && lottieImage != null
        }

    val product: PayDetail? get() = discountInfoManager.discountInfo?.actList?.firstOrNull()?.productList?.firstOrNull()

    val firstActive: SubPreferential? get() = discountInfoManager.discountInfo?.actList?.firstOrNull()

    fun init() {
        if (!UserManager.isLogin()) return
        applicationScope.launchSafety {
            val info = doContinuousOperation { discountInfoManager.fetchDiscountInfo() } ?: return@launchSafety
            val iconDeffer = async(Dispatchers.IO) { downloadIcon() }
            val imageDeffer = async(Dispatchers.IO) { downloadImage() }
            awaitAll(iconDeffer, imageDeffer)
            if (iconFile != null && lottieImage != null) {
                eventDispatcher.emitDiscountInfo(info)
            }
        }
    }

    private suspend fun downloadIcon() {
        if (isLoadingIcon) return
        doContinuousOperation {
            val iconUrl = discountInfoManager.discountInfo?.actList?.firstOrNull()?.iconUrl.orEmpty()
            isLoadingIcon = true
            val fileName = iconUrl.substringAfterLast("/")
            if (iconUrl.isNotEmpty() && fileName.isNotEmpty()) {
                fileDownloader.downloadFile(iconUrl, fileName)
            }
        }
        isLoadingIcon = false
    }

    private suspend fun downloadImage() {
        if (isLoadingImage) return
        doContinuousOperation {
            val picUrl = discountInfoManager.discountInfo?.actList?.firstOrNull()?.picUrl.orEmpty()
            isLoadingImage = true
            val fileName = picUrl.substringAfterLast("/")
            if (picUrl.isNotEmpty() && fileName.isNotEmpty()) {
                fileDownloader.downloadFile(picUrl, fileName)
            }
        }
        isLoadingImage = false
    }

    val iconFile: File?
        get() {
            val iconUrl = discountInfoManager.discountInfo?.actList?.firstOrNull()?.iconUrl ?: return null
            val fileName = iconUrl.substringAfterLast("/")
            val file = File(appContext.filesDir, fileName)
            if (file.exists()) return file
            applicationScope.launchSafety {
                downloadIcon()
            }
            return null
        }

    val lottieImage: File?
        get() {
            val picUrl = discountInfoManager.discountInfo?.actList?.firstOrNull()?.picUrl ?: return null
            val fileName = picUrl.substringAfterLast("/")
            val file = File(appContext.filesDir, fileName)
            if (file.exists()) return file
            applicationScope.launchSafety {
                downloadImage()
            }
            return null
        }

    fun LottieAnimationView.playEnter() {
        val file = iconFile
        if (file != null && tag != file.name) {
            tag = file.name
            lottieFileLoader.loadAnimFile(this, file)
        }
    }

    fun LottieAnimationView.playImage() {
        val file = lottieImage
        if (file != null && tag != file.name) {
            tag = file.name
            lottieFileLoader.loadAnimFile(this, file)
        }
    }
}